package worker;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import masterserver.TalkToCodeServer;


import result.ClassRequest;


public class RemoteClassLoader extends ClassLoader { 

	private int problemNumber;
	private int version;
	private TalkToCodeServer talkToCodeServer;
	private ObjectOutputStream outStream;
	private ObjectInputStream  inStream;

	

	public RemoteClassLoader(TalkToCodeServer talkToCodeServer) {
		this.talkToCodeServer = talkToCodeServer;
	}
	public RemoteClassLoader(int problemNumber, int version,TalkToCodeServer talkToCodeServer) {
		super();
		this.problemNumber = problemNumber;
		this.version = version;
		this.talkToCodeServer = talkToCodeServer;
	}


	public void setProblemNumber(int problemNumber) {
		this.problemNumber = problemNumber;
	}


	public void setVersion(int version) {
		this.version = version;
	}


	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		System.out.println("vai pedir class:"+name);
		if(outStream==null && inStream == null){
			System.out.println("talkserver:");
	 //   talkToCodeServer.lock();
		talkToCodeServer.sendObject((new ClassRequest(problemNumber, version, name)));	
		System.out.println("Ask for class " + name);
		byte[] classInfo = (byte[])talkToCodeServer.receiveObject();
	//	talkToCodeServer.unLock();
		return defineClass(name,classInfo, 0, classInfo.length);
		}
		else
			try {
				System.out.println("vai pedir class:"+name);
				outStream.writeObject(new ClassRequest(problemNumber, version, name));	
				System.out.println("Ask for class " + name);
				byte[] classInfo = (byte[]) inStream.readObject();
				System.out.println("Got " + classInfo);
				return defineClass(name,classInfo, 0, classInfo.length);
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("Saiu por aqui");
				throw new ClassNotFoundException(name + " - " + e.toString());
			}
		
	}

	
}
